from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from datetime import timedelta
from typing import Any
import uuid

from app.core.config import settings
from app.core.security import create_access_token
from app.api.deps import get_current_user
from app.db.session import get_db
from app.crud import user as user_crud
from app.schemas.user import UserCreate, UserLogin, PasswordReset, Token, UserProfile
from app.models.user import User
from app.core import security

router = APIRouter()

@router.post("/register", response_model=UserProfile)
def register(*, db: Session = Depends(get_db), user_in: UserCreate) -> Any:
    """注册新用户"""
    # 验证密码确认
    if user_in.password != user_in.confirm_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="两次输入的密码不一致"
        )

    # 检查邮箱是否已注册
    db_user = user_crud.get_user_by_email(db, email=user_in.email)
    if db_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该邮箱已注册"
        )

    # 创建新用户
    try:
        user = user_crud.create_user(db, user_in)
        return user
    except Exception as e:
        print(f"创建用户失败: {e}")  # 添加错误日志
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="创建用户失败"
        )

@router.post("/login", response_model=Token)
def login(*, db: Session = Depends(get_db), user_in: UserLogin) -> Any:
    """用户登录"""
    try:
        user = user_crud.authenticate_user(db, user_in.email, user_in.password)
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="邮箱或密码错误"
            )
        elif not user.is_active:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户已被禁用"
            )

        # 更新最后登录时间
        user_crud.update_last_login(db, user.id)

        # 修改返回结构，增加用户信息
        return {
            "access_token": security.create_access_token(user.id),
            "token_type": "bearer",
            "user": {
                "id": user.id,
                "email": user.email,
                "nickname": user.nickname,
                "create_time": user.create_time,  # 确保包含这个字段
                "avatar": user.avatar,
                "last_login_time": user.last_login_time
            }
        }
    except HTTPException:
        raise
    except Exception as e:
        print(f"登录失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="登录失败"
        )

@router.post("/reset-password")
def reset_password(
    *,
    db: Session = Depends(get_db),
    reset_in: PasswordReset,
    current_user_id: str = Depends(security.get_current_user_id)
) -> Any:
    """重置密码"""
    try:
        # 验证当前用户
        user = user_crud.get_user(db, user_id=current_user_id)
        if not user or user.email != reset_in.email:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="用户验证失败"
            )

        # 验证旧密码
        if not security.verify_password(reset_in.old_password, user.hashed_password):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="旧密码错误"
            )

        # 更新密码
        user_crud.update_password(db, user.id, reset_in.new_password)
        return {"message": "密码修改成功"}
    except HTTPException:
        raise
    except Exception as e:
        print(f"重置密码失败: {e}")  # 添加错误日志
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="重置密码失败"
        )
